"""
FastAPI 保险管理系统主应用
"""
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from tortoise.contrib.fastapi import register_tortoise

from .config.settings import settings
from .config.database import TORTOISE_ORM
from .api.v1.api import api_router


def create_app() -> FastAPI:
    """创建 FastAPI 应用"""
    
    # 创建 FastAPI 实例
    app = FastAPI(
        title=settings.app_name,
        version=settings.app_version,
        debug=settings.debug,
        description="保险管理系统 API",
        docs_url="/docs",
        redoc_url="/redoc",
        openapi_url="/openapi.json"
    )
    
    # 配置 CORS 中间件
    app.add_middleware(
        CORSMiddleware,
        allow_origins=settings.allowed_origins,
        allow_credentials=True,
        allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
        allow_headers=["*"],
    )
    
    # 注册 API 路由
    app.include_router(
        api_router,
        prefix=settings.api_v1_prefix
    )
    
    # 注册 Tortoise ORM
    register_tortoise(
        app,
        config=TORTOISE_ORM,
        generate_schemas=True,  # 自动创建表结构
        add_exception_handlers=True,  # 添加异常处理
    )
    
    return app


# 创建应用实例
app = create_app()
print("项目启动成功！！")

@app.get("/", tags=["根路径"])
async def root():
    """根路径"""
    return {
        "message": f"欢迎使用 {settings.app_name}",
        "version": settings.app_version,
        "docs": "/docs"
    }


@app.get("/health", tags=["健康检查"])
async def health_check():
    """健康检查端点"""
    return {
        "status": "healthy",
        "service": settings.app_name,
        "version": settings.app_version
    }